package com.ccteam.shared.domain.moment.comment

import android.content.Context
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.model.moment.comment.CommentVO
import com.ccteam.shared.api.MomentsDataSource
import com.ccteam.shared.data.moment.MomentDetailCommentPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.moment.comment.MomentCommentItem
import com.ccteam.shared.result.moment.comment.MomentReplayItem
import com.ccteam.shared.utils.EMPTY_STRING
import com.ccteam.shared.utils.MOMENT_QUALITY
import com.ccteam.shared.utils.PHOTO_QUALITY
import com.ccteam.shared.utils.transToDateReciprocal
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/28
 */
class MomentDetailCommentDataUseCase @Inject constructor(
    @ApplicationContext private val context: Context,
    private val momentsDataSource: MomentsDataSource
): PagingUseCase<String?, MomentCommentItem>(
    Dispatchers.IO
) {
    override fun execute(parameters: String?): Flow<PagingData<MomentCommentItem>> {
        if(parameters.isNullOrEmpty()){
            return flowOf(PagingData.empty())
        }
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            MomentDetailCommentPagingSource(parameters,momentsDataSource)
        }.flow.map { pagingData ->
            pagingData.map {
                transformToMomentCommentItem(it)
            }
        }
    }

    private fun transformToMomentCommentItem(commentInfoVO: CommentVO): MomentCommentItem{
        return MomentCommentItem(
            commentInfoVO.id,commentInfoVO.momentId,commentInfoVO.content,commentInfoVO.user.id,
            commentInfoVO.user.name,commentInfoVO.createTime.transToDateReciprocal(context),
            commentInfoVO.user.photoUrl + PHOTO_QUALITY,
            commentInfoVO.replyNum ?: 0,commentInfoVO.type,commentInfoVO.replyDetails?.map {
                MomentReplayItem(it.id,it.momentId,it.commentId,it.content,it.user.id,it.user.name,
                    it.createTime.transToDateReciprocal(context),
                    it.user.photoUrl + PHOTO_QUALITY,it.toUser.id,it.toUser.name,
                    commentInfoVO.replyNum ?: 0,it.type)
            } ?: emptyList()
        )
    }
}